$.validator.setDefaults({
    highlight: function (element) {
        $(element).closest('.form-group').removeClass('has-success').addClass('has-error');
    },
    success: function (element) {
        element.closest('.form-group').removeClass('has-error').addClass('has-success');
    },
    errorElement: "span",
    errorPlacement: function (error, element) {
        if (element.is(":radio") || element.is(":checkbox")) {
            error.appendTo(element.parent().parent().parent());
        } else {
            error.appendTo(element.parent());
        }
    },
    errorClass: "help-block m-b-none",
    validClass: "help-block m-b-none"
});
$(document).ready(function() {
	/**
	 * 获取数据到datatable
	 */
	var getTownData = function(sSource,aoData,fnCallback){
		$.ajax({
    		url:sSource,
    		type : "post",
    		data:{
    			"aoData":JSON.stringify(aoData)
    		},
    		dataType : "json",
    		success:function(result){
    			fnCallback(result);
    		},error:function(msg){
    			console.info(msg);
    		}
    	});
	};
	
	/**
	 * datatable
	 */
	$("#towntable").dataTable({
		"order": [[ 3, "asc" ]],
		"language": {
			"processing": "数据加载中...",
	        "emptyTable": "未找到匹配记录",
	        "info": "第_START_到_END_条记录,共_TOTAL_条记录",
	        "sInfoFiltered":"",
	        "infoEmpty": "没有找到记录",
	        "lengthMenu": "显示 _MENU_ 条记录",
	        "search": "搜索:"
        },
	    "columnDefs":[
		    {"data":"townid",'targets': [0],"title":"镇编号",'Sortable': false,"visible": false},
		    {"data":"townname",'targets': [1],"title":"镇名称", "bSortable": false},
		    {"data":"townkeyvalue",'targets': [2],"title":"镇key", "bSortable": false,
		    	"render":function(data, type, full){
		    		if(full.townkeyvalue===""||full.townkeyvalue===undefined)
                		return "<span style='color:red;'>无</span>";
                    else
                    	return full.townkeyvalue;
		    	}
		    },{"data":"townsort",'targets': [3],"title":"排序",
		    	"render":function(data, type, full){
		    		if(full.townsort===""||full.townsort===undefined)
                		return "<span style='color:red;'>无</span>";
                    else
                    	return full.townsort;
		    	}
		    },{'targets': [4],"title":"操作","bSortable": false,
		    	"render":function(data,type,full){
		    		return "<button onclick='alert("+full.townsort+");'>操作</button>";
		    	}
		    }
		],
		"bAutoWidth":false,
		"bServerSide": true,//这个用来指明是通过服务端来取数据
		"bProcessing": true, // 是否显示取数据时的那个等待提示
		"sAjaxSource":"../town/datatable",
		"fnServerData":getTownData
	});
	
	
	/**
	 * 添加镇信息表单验证
	 */
	var icon = "<i class='fa fa-times-circle'></i> ";
	var validatorAddRow = $("#addRowForm").validate({
        errorClass: 'help-block help-block-error', 
        focusInvalid: false,ignore: "",  
		rules: {
            townname: {
                required: true,
                minlength: 2
            },townsort:{
            	number:true
            }
        },messages: {
        	townname: {
                required: icon + "请输入镇名称",
                minlength: icon + "镇名称必须两个字符以上"
            },townsort:{
            	number:"排序号必须为数字"
            }
        },highlight: function (element) { 
            $(element).closest('.form-group').addClass('has-error'); 
        },unhighlight: function (element) {
            $(element).closest('.form-group').removeClass('has-error'); 
        },success: function (label) {
            label.closest('.form-group').removeClass('has-error'); 
        },onfocusout: function(element) {
        	$(".msg").html("");
        	$(element).valid(); 
        },onfocusin:function(element){
        	$(".msg").html("");
        }
	});
	
	
	$("#submitAdd").bind("click",function(){
		submit();
	});
	
	$("#addRowBtn").bind("click",function(){
		$.get("../town/maxsort",function(data){
			if(data.code==0){
				$("#townsort").attr("placeholder","请输入排序号！当前最大值（"+data.data+"）");
			}
		});
	});
	
	var submit = function(){
		if($('#addRowForm').validate().form()){
			$.ajax({
				data:$('#addRowForm').serialize(),
				type: "POST",
				url:"../town/save",
				success:function(data){
					if(data.code==0){
						window.location.href="index.jsp"
					}else{
						$(".msg").html("<div class='alert alert-danger'>用户名或密码错误！</div>");
						$(".has-error").removeClass("has-error");
						validator.resetForm();
					}
				},error:function(a,b,c){
					$(".msg").html("<div class='alert alert-danger'>系统错误！</div>");
				}
			});
		}
	}
	
	
	var handleAddRow = function(){
		
	};
	
	
});


